from django.http import HttpResponse
from common import *
from wakeonlan import send_magic_packet
import os

def wake_on_lan(mac=MAC_ADDR):
    commond = "etherwake {}".format(MAC_ADDR)
    os.system("echo {}|sudo -S {}".format(SUDOPASSWORD,commond))


def wake(request):
    try:
        if PASSWORD!="" and request.GET.get('p')!=PASSWORD:
            return HttpResponse('<h1>Invalid Password!</h1>')
        wake_on_lan()
        return HttpResponse('<h1>SUCCESS</h1>')
    except Exception as e:
        return HttpResponse(repr(e),status=500)


def status(request):
    if PASSWORD != "" and request.GET.get('p') != PASSWORD:
        return HttpResponse('<h1>Invalid Password!</h1>')
    visit_IP = os.popen('ping {} -c 5'.format(IP))
    result = visit_IP.read()
    visit_IP.close()
    if 'TTL' in result or 'ttl' in result:
        return HttpResponse('<h1>ONLINE</h1>')
    else:
        return HttpResponse('<h1>OFFLINE</h1>')

